package com.by.interceptor;

import com.by.token.Result;
import com.by.token.TokenTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author 江俊俊
 * @version 1.0
 * @description
 * @date 2025/2/12 19:21
 * @since JDK1.8
 */
public class TokenInterception implements HandlerInterceptor {

    TokenTemplate tokenTemplate;

    public TokenInterception(TokenTemplate tokenTemplate) {
        this.tokenTemplate = tokenTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null ) {
            fail(response,"没有token，无法访问");
            return false;
        }
        Result result = tokenTemplate.valid(token);
        if (result.getCode() != 3) {
            fail(response,result.getMsg());
            return false;
        }
        Map map = result.getPayload();
        return true;
    }

    void fail(HttpServletResponse response,String msg) {
        response.setContentType("application/json;charset=UTF-8");
        try (PrintWriter pw = response.getWriter()) {
            pw.println("{\"code\":0,\"msg\":\"" + msg + "\"}");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
